package com.watson.minio.springminio.minio.config;

import io.minio.MinioClient;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *  https://blog.csdn.net/wang926454/article/details/106410669?spm=1001.2101.3001.6650.11&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-11.pc_relevant_aa&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-11.pc_relevant_aa&utm_relevant_index=13
 *
 * @author: llun
 * @date: 2022/1/24 10:01
 * @version: 1.0
 */
@Configuration
@Data
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    private final static Logger logger = LoggerFactory.getLogger(MinioConfig.class);

    //    @Value("${minio.url}")
    private String url;

    //    @Value("${minio.access}")
    private String access;

    //    @Value("${minio.secret}")
    private String secret;

    //    @Value("${minio.bucket}")
    private String bucket;


    /**
     * 初始化 MinioClient 自动注入到 spring 容器
     *
     * @return
     * @throws Exception
     */
    @Bean(name = "minioClient")
    @ConditionalOnProperty(prefix = "minio",name = "enable",havingValue = "true",matchIfMissing = true)
    public MinioClient minioClient() throws Exception {
        logger.info("---------- Minio文件系统初始化加载 ----------");
        MinioClient minioClient = new MinioClient(url, access, secret);
        // 判断Bucket是否存在
        boolean isExist = minioClient.bucketExists(bucket);
        if (isExist) {
            logger.info("---------- Minio文件系统Bucket已存在 ----------");
        } else {
            // 不存在创建一个新的Bucket
            minioClient.makeBucket(bucket);
            logger.info("---------- Minio文件系统Bucket已创建 ----------");
        }
        logger.info("---------- Minio文件系统初始化完成 ----------");
        return minioClient;
    }


}
